import { useEffect, useRef } from 'react';
import './style.css';

export interface YuqueViewerProps {
  className?: string;
  style?: React.CSSProperties;
  content?: string;
}

declare global {
  interface Window {
    Doc: {
      createOpenEditor: (element: HTMLElement, config: any) => any;
      createOpenViewer: (element: HTMLElement, config: any) => any;
      toolbarItems: Record<string, any>;
    };
  }
}

export function YuqueViewer({
  className = '',
  style = {},
  content = '<p><span style="color: rgb(255, 111, 4),rgb(243, 48, 171)">欢迎来到yuque阅读器</span></p>'
}: YuqueViewerProps) {
  const viewerRef = useRef<HTMLDivElement>(null);
  const viewerInstanceRef = useRef<any>(null);

  useEffect(() => {
    let retryCount = 0;
    const maxRetries = 5;
    const retryInterval = 1000; // 1秒

    const initViewer = () => {
      if (!viewerRef.current || !window.Doc) {
        if (retryCount < maxRetries) {
          retryCount++;
          console.log(`重试初始化阅读器 (${retryCount}/${maxRetries})...`);
          setTimeout(initViewer, retryInterval);
          return;
        }
        console.error('阅读器初始化失败：无法加载Doc对象');
        return;
      }

      try {
        const { createOpenViewer } = window.Doc;
        const viewer = createOpenViewer(viewerRef.current, {});

        viewer.setDocument('text/lake', content);

        viewerInstanceRef.current = viewer;
        console.log('阅读器初始化成功');
      } catch (error) {
        console.error('阅读器初始化错误:', error);
      }
    };

    // 确保DOM和脚本都已加载
    if (document.readyState === 'complete') {
      initViewer();
    } else {
      window.addEventListener('load', initViewer);
    }

    return () => {
      window.removeEventListener('load', initViewer);
    };
  }, [content]);

  return (
    <div className={`yuque-viewer ${className}`} style={{ height: '100%', ...style }}>
      <div ref={viewerRef} className="ne-doc-major-viewer" style={{ height: '100%' }}></div>
    </div>
  );
} 